﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IMC.Prepare.Core.Infrastructure.DependencyManagement;
using Autofac;

namespace IMC.Prepare.Core.Infrastructure
{
    public class NopEngine : IEngine
    {
        #region Fields

        private ContainerManager _containerManager;

        #endregion

        public NopEngine()
            : this(new ContainerConfigurer())
        {
        }

        public NopEngine(ContainerConfigurer configurer)
        {
            //var config = ConfigurationManager.GetSection("NopConfig") as NopConfig;
            //InitializeContainer(configurer, broker, config);
            InitializeContainer(configurer);
        }

        private void InitializeContainer(ContainerConfigurer configurer)
        {
            var builder = new ContainerBuilder();

            _containerManager = new ContainerManager(builder.Build());
            configurer.Configure(this, _containerManager);
        }

        public object Resolve(Type type)
        {
            return ContainerManager.Resolve(type);
        }

        public T Resolve<T>() where T : class
        {
            return ContainerManager.Resolve<T>();
        }

        public void Initialize()
        {
            //startup tasks
            RunStartupTasks();
        }

        private void RunStartupTasks()
        {
            var typeFinder = _containerManager.Resolve<ITypeFinder>();
            var startUpTaskTypes = typeFinder.FindClassesOfType<IStartupTask>();
            var startUpTasks = new List<IStartupTask>();
            foreach (var startUpTaskType in startUpTaskTypes)
                startUpTasks.Add((IStartupTask)Activator.CreateInstance(startUpTaskType));
            //sort
            startUpTasks = startUpTasks.AsQueryable().OrderBy(st => st.Order).ToList();
            foreach (var startUpTask in startUpTasks)
                startUpTask.Execute();
        }

        #region Properties

        public IContainer Container
        {
            get { return _containerManager.Container; }
        }

        public ContainerManager ContainerManager
        {
            get { return _containerManager; }
        }

        #endregion
    }
}
